package gitee.derumin.teleport_compass.mixin;

import gitee.derumin.teleport_compass.waypoints.WaypointLinked;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.decoration.DisplayEntity;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(DisplayEntity.class)
public abstract class DisplayEntityMixin extends Entity implements WaypointLinked {
    @Unique private boolean linked = false;
    @Unique private boolean shouldKill = false;

    public DisplayEntityMixin(EntityType<?> entityType, World world) {
        super(entityType, world);
    }

    @Override
    public void teleport_compass$setLinked(){
        this.linked = true;
    }

    @Inject(method = "writeCustomDataToNbt", at = @At("RETURN"))
    private void recordIfLinked(NbtCompound nbt, CallbackInfo ci){
        nbt.putBoolean("should_kill", this.linked);
    }

    @Inject(method = "readCustomDataFromNbt", at = @At("RETURN"))
    private void readLinked(NbtCompound nbt, CallbackInfo ci){
        if (nbt.contains("should_kill")){
            this.shouldKill = nbt.getBoolean("should_kill");
        }
    }

    @Inject(method = "tick", at = @At("HEAD"))
    private void selfKill(CallbackInfo ci){
        if (this.shouldKill){
            this.kill();
        }
    }
}
